import {
    Injectable,
    NestInterceptor,
    ExecutionContext,
    CallHandler,
    HttpStatus,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Request, Response } from 'express';

export interface ResponseType<T> {
    data: T;
    code: number;
    message: string;
}

@Injectable()
export class TransformInterceptor<T>
    implements NestInterceptor<T, ResponseType<T>>
{
    intercept(
        context: ExecutionContext,
        next: CallHandler,
    ): Observable<ResponseType<T>> {
        // 因为nestjs使用REST API风格，对于post请求默认返回201，所以需要手动处理成200
        const request = context.switchToHttp().getRequest<Request>();
        const response = context.switchToHttp().getResponse<Response>();
        if (
            request.method === 'POST' &&
            response.statusCode === HttpStatus.CREATED
        ) {
            response.status(HttpStatus.OK);
        }

        return next.handle().pipe(
            map((data) => {
                return {
                    data: data.data,
                    code: data.code,
                    message: data.message,
                    success: true,
                    timeStamp: new Date().getTime(),
                };
            }),
        );
    }
}
